package lew.bing.exp.net.exa1;

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.util.ReferenceCountUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * Created by 刘国兵 on 2018/7/30.
 */
public class DiscardServerHandler extends ChannelInboundHandlerAdapter { // 首先需要继承自该类

    private static final Logger logger = LoggerFactory.getLogger(DiscardServerHandler.class);

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {// 读取的方法
//        super.channelRead(ctx, msg);
//        ((ByteBuf) msg).release();// msg是ByteBug类型，可以release
        // 通常做法
        ByteBuf in = (ByteBuf) msg;
        try {
            // todo something
            while (in.isReadable()) {
                System.out.print((char) in.readByte());
                System.out.flush();

            }

        } finally {
            ReferenceCountUtil.release(msg); // 这样也能释放
        }
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {// 异常处理的方法
        logger.error("discardServer get error =>",cause);
        ctx.close();// 关闭上下文
    }
}
